#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>

#define MYPORT 5000
#define MAXBUFLEN 100

int main()
{
    int sockfd;
    struct sockaddr_in my_addr; // 本机的地址信息
    struct sockaddr_in their_addr; // 连接本机的地址信息
    int addr_len, numbytes;
    char buf[MAXBUFLEN];

    if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    my_addr.sin_family = AF_INET; // 主机字节序
    my_addr.sin_port = htons(MYPORT); // 网络字节序
    my_addr.sin_addr.s_addr = INADDR_ANY; // 自动设置为自己的IP
    bzero(&(my_addr.sin_zero), 8); // 清零

    if(bind(sockfd, (struct sockadd*)&my_addr, sizeof(struct sockaddr)) == -1) {
        perror("bind");
        exit(1);
    }

    addr_len = sizeof(struct sockaddr);
    if((numbytes = recvfrom(sockfd, buf, MAXBUFLEN, 0, (struct sockaddr*)&their_addr, &addr_len)) == -1) {
        perror("recvfrom");
        exit(1);
    }

    printf("got packet from %s\n", inet_ntoa(their_addr.sin_addr));
    printf("packet is %d bytes long\n", numbytes);
    buf[numbytes] = '\0';
    printf("packet contains \"%s\"\n", buf);

    close(sockfd);
}